<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class TopicCategory extends Model
{
    use HasDateTimeFormatter;

    protected $table = 'topic_categories';

    public $timestamps = false;

    protected $cacheKey = 'topicCategoryList';

    public function topic()
    {
        return $this->hasMany(Topic::class, 'category_id', 'id');
    }

    public function getList($where = [], $with = [])
    {

        return $this->newQuery()
            ->when($where, function ($query, $where) {
                return $query->where($where);
            })
            ->when($with, function ($query, $with) {
                return $query->with($with);
            })
            ->orderBy('sort')
            ->get()
            ->toArray();
    }

    // 从缓存中获取
    public function getCacheList()
    {
        $key = $this->cacheKey;
        $data = Cache::rememberForever($key, function () {
            return $this->newQuery()
                ->where(['switch' => 1])
                ->get()
                ->toArray();
        });

        return $data;
    }

    /**
     * 获取首页导航栏
     * 增加首页
     * @return array
     */
    public function getNavs() : array
    {
        $data = $this->getCacheList();
        array_unshift($data, ['id' => 0, 'name' => '首页']);
        return $data;
    }

    /**
     * 获取发布分类
     * 去掉公告
     * @return array
     */
    public function getPublishCate() : array
    {
        $data = $this->getCacheList();
        $list = [];
        foreach ($data as $k => $v) {
            if ($v['name'] != '公告') {
                $list[] = $v;
            }
        }

        return $list;
    }

}
